/*
 * FilePath     : \src\utils\http.ts
 * Author       : SJZ
 * Date         : 2025-03-12 19:28
 * LastEditors  : SJZ
 * LastEditTime : 2025-03-12 20:02
 * Description  : axios的二次封装
 * CodeIterationRecord: 
 */

import { Loading } from "./enum";
import axios from "axios";
import type { AxiosRequestConfig } from "axios";
import qs from "qs";

const axiosInstance = axios.create({
  withCredentials: false
});

axiosInstance.interceptors.request.use(
  (config: any) => {
    const authorization = common.session("session")?.authorization ?? "";
    // 头部设置token
    config.headers.Authorization = authorization ? `Bearer ${authorization}` : "";
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axiosInstance.interceptors.response.use(
  (response) => {
    if (response?.status === 200) {
      return Promise.resolve(response.data);
    } else {
      return Promise.reject(response);
    }
  },
  (error) => {
    if (error.status == 401) {
      showMessage("warning", "登陆超时！请重新登录!");
    }
    return error;
  }
);

/**
 * @description: 设置ApiUrl
 * @param url ApiUrl
 * @return
 */
export const setApiUrl = (url: string) => {
  axiosInstance.defaults.baseURL = url;
};

const request = <ResponseType = unknown>(url: string, method: string, params?: AxiosRequestConfig<unknown>): Promise<ResponseType> => {
  // 设置请求头
  const config: AxiosRequestConfig = {
    method,
    ...(method === "get" ? { params } : { data: params })
  };

  return new Promise((resolve, reject) => {
    axiosInstance({ url, ...config })
      .then((res: any) => {
        if (res?.message && res?.code == 0) {
          showMessage("warning", res.message);
        }
        resolve(res?.data);
      })
      .catch((err) => reject(err));
  });
};

import { useRequest, useFetchs, useTimeout } from "vue-hooks-plus";
import useSessionStore from "@/stores/modules/session";
let clearLoadingTimeout: any = undefined;
const isUseRequest = (url: string, requestType: string = "get", config: RequestConfig) => {
  const sessionStore = useSessionStore();
  const { qsFlag = false, loadingText = Loading.LOAD } = config;
  const { runAsync } = useRequest((params: any) => request(url, requestType, qsFlag ? qs.stringify(params) : params), {
    manual: true,
    debounceWait: 300,
    throttleWait: 1000,
    throttleTrailing: false,
    formatResult(res) {
      if (!config.formatDateView) {
        return res;
      }
      const data = common.resultFormat(res, config.formatDateView);
      return data;
    },
    onBefore: () => {
      if (clearLoadingTimeout) {
        clearLoadingTimeout();
        clearLoadingTimeout = undefined;
      }
      sessionStore.$patch((store) => {
        store.loading++;
        store.loadingText = loadingText;
      });
    },
    onSuccess: () => {},
    onError: (error: any) => {
      error && showMessage("error", error);
    },
    onFinally: () => {
      clearLoadingTimeout = useTimeout(() => {
        sessionStore.$patch((store) => {
          store.loading--;
          store.loading < 0 && (store.loading = 0);
          store.loadingText = "";
        });
      }, 400);
    }
  });
  return runAsync;
};

const isFetchs = (url: string, requestType: string = "get", config: RequestConfig) => {
  const { qsFlag = false, loadingText = Loading.LOAD } = config;
  const { fetchRun, fetchs } = useFetchs(
    (params: any) => request(url, requestType, qsFlag ? qs.stringify(params) : params),
    {
      manual: true,
      onBefore: (params: any) => {
      },
      onSuccess: (data: any) => {},
      onError: (error: any) => {
        error && showMessage("error", error);
      },
      onFinally: () => {
        // hideLoading();
      }
    },
    {
      fetchKey: (params) => {
        return params.dataKey;
      }
    }
  );
  return { fetchRun, fetchs };
};
/**
 * @description: 请求API
 * @param url 地址
 * @param requestType get post
 * @param batchFlag 是不是批量执行
 * @return
 */
export const http = (url: string, requestType: string = "get", config: RequestConfig = {}) => {
  const { batchRequestFlag = false } = config;
  const currentRequest = batchRequestFlag ? isFetchs(url, requestType, config) : isUseRequest(url, requestType, config);
  return currentRequest as any;
};
export default { setApiUrl, http };
